package com.ruoyi.framework.web.service;

import javax.annotation.Resource;

import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.utils.*;
import com.ruoyi.common.utils.http.HttpUtils;
import com.ruoyi.common.utils.uuid.IdUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Component;
import com.ruoyi.common.constant.CacheConstants;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.exception.user.CaptchaException;
import com.ruoyi.common.exception.user.CaptchaExpireException;
import com.ruoyi.common.exception.user.UserPasswordNotMatchException;
import com.ruoyi.common.utils.ip.IpUtils;
import com.ruoyi.framework.manager.AsyncManager;
import com.ruoyi.framework.manager.factory.AsyncFactory;
import com.ruoyi.system.service.ISysConfigService;
import com.ruoyi.system.service.ISysUserService;

import java.util.HashMap;
import java.util.Random;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * 登录校验方法
 *
 * @author ruoyi
 */
@Component
public class SysLoginService {

    private Logger logger = LoggerFactory.getLogger(SysLoginService.class);
    @Autowired
    private TokenService tokenService;

    @Resource
    private AuthenticationManager authenticationManager;

    @Autowired
    private RedisCache redisCache;

    @Autowired
    private ISysUserService userService;

    @Autowired
    private ISysConfigService configService;

    // 是否允许账户多终端同时登录（true允许 false不允许）
    @Value("${token.soloLogin}")
    private boolean soloLogin;

    /**
     * 登录验证
     *
     * @param username 用户名
     * @param password 密码
     * @param code     验证码
     * @param uuid     唯一标识
     * @return 结果
     */
    public String login(String username, String password, String code, String uuid) {
/*        boolean captchaOnOff = configService.selectCaptchaOnOff();
        // 验证码开关
        if (captchaOnOff) {
            validateCaptcha(username, code, uuid);
        }*/
        // 用户验证
        Authentication authentication = null;
        try {
            // 该方法会去调用UserDetailsServiceImpl.loadUserByUsername
            authentication = authenticationManager
                    .authenticate(new UsernamePasswordAuthenticationToken(username, password));
        } catch (Exception e) {
            if (e instanceof BadCredentialsException) {
                AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("user.password.not.match")));
                throw new UserPasswordNotMatchException();
            } else {
                AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, e.getMessage()));
                throw new ServiceException(e.getMessage());
            }
        }
        AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_SUCCESS, MessageUtils.message("user.login.success")));
        LoginUser loginUser = (LoginUser) authentication.getPrincipal();
        recordLoginInfo(loginUser.getUserId());
        clearLockLoginFor5times(username);

        if (!soloLogin) {
            // 如果用户不允许多终端同时登录，清除缓存信息
            String userIdKey = CacheConstants.LOGIN_USERID_KEY + loginUser.getUser().getUserId();
            String userKey = redisCache.getCacheObject(userIdKey);
            if (StringUtils.isNotEmpty(userKey)) {
                redisCache.deleteObject(userIdKey);
                redisCache.deleteObject(userKey);
            }
        }

        // 生成token
        String token = tokenService.createToken(loginUser);
        if (RuoYiConfig.isNeedCheckSms()) {
            // 返回短信通知的key，前台回传
            return generateSmsKeyMap(token);
        } else {
            return token;
        }
    }

    public String smsCheck(String smsKey, String smsValue) {
        String smsRealKey = CacheConstants.LOGIN_USER_SMS_KEY + smsKey;
        HashMap<String, Object> smsKeyMap = redisCache.getCacheObject(smsRealKey);
        if (smsKeyMap == null) {
            return null;
        }
        String smsCode = (String) smsKeyMap.get("smsCode");
        if (!smsValue.equals(smsCode)) {
            return null;
        }
        return (String) smsKeyMap.get("token");
    }

    public String resendSms(String smsKey) {
        return refreshSmsKeyMap(smsKey);
    }


    /**
     * 校验验证码
     *
     * @param username 用户名
     * @param code     验证码
     * @param uuid     唯一标识
     * @return 结果
     */
    public void validateCaptcha(String username, String code, String uuid) {
        String verifyKey = CacheConstants.CAPTCHA_CODE_KEY + StringUtils.nvl(uuid, "");
        String captcha = redisCache.getCacheObject(verifyKey);
        redisCache.deleteObject(verifyKey);
        if (captcha == null) {
            AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("user.jcaptcha.expire")));
            throw new CaptchaExpireException();
        }
        if (!code.equalsIgnoreCase(captcha)) {
            AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("user.jcaptcha.error")));
            throw new CaptchaException();
        }
    }

    /**
     * 记录登录信息
     *
     * @param userId 用户ID
     */
    public void recordLoginInfo(Long userId) {
        SysUser sysUser = new SysUser();
        sysUser.setUserId(userId);
        sysUser.setLoginIp(IpUtils.getIpAddr(ServletUtils.getRequest()));
        sysUser.setLoginDate(DateUtils.getNowDate());
        userService.updateUserProfile(sysUser);
    }


    public String generateSmsKeyMap(String token) {
        HashMap<String, Object> resultMap = new HashMap<>();
        String smsTokenKey = IdUtils.fastUUID();
        String smsCode = generateSmsCode();
        HashMap<String, Object> redisSaveMap = new HashMap<>();
        redisSaveMap.put("smsCode", smsCode);
        redisSaveMap.put("token", token);
        redisCache.setCacheObject(CacheConstants.LOGIN_USER_SMS_KEY + smsTokenKey, redisSaveMap, 300, TimeUnit.SECONDS);


        LoginUser loginUser = tokenService.getLoginUserByJwtToken(token);
        if (!checkIsPhoneNumber(loginUser.getUser().getPhonenumber())) {
            return Constants.ERROR_PHONE_NOT_BIND;
        }

        // 发送 smsCode 到用户手机
        String uuid = 1 + "_" + UUID.randomUUID();
        String param = "uuid=" + uuid + "&called=" + loginUser.getUser().getPhonenumber() + "&content=" + smsCode;
        String body = HttpUtils.sendPost("http://{IP}:{PORT}/api/sendMessage", param);
        logger.info("短信验证码接口响应:{}", body);


        return smsTokenKey;
    }

    /**
     * 记录登录5次的账号锁定
     */
    public boolean lockLoginFor5times(String userName, int maxCount) {
        boolean lockFlag = false;
        String redisUsernameKey = Constants.LOGIN_USER_NAME_KEY + userName;
        if (redisCache.getCacheObject(redisUsernameKey) != null) {
            int keyCount = redisCache.getCacheObject(redisUsernameKey);
            if (keyCount <= maxCount) {
                keyCount++;
                redisCache.setCacheObject(redisUsernameKey, keyCount, 15, TimeUnit.MINUTES);
            } else {
                lockFlag = true;
            }
        } else {
            redisCache.setCacheObject(redisUsernameKey, 1, 15, TimeUnit.MINUTES);
        }
        return lockFlag;
    }

    public String refreshSmsKeyMap(String smsKey) {
        String smsRealKey = CacheConstants.LOGIN_USER_SMS_KEY + smsKey;
        HashMap<String, Object> smsKeyMap = redisCache.getCacheObject(smsRealKey);
        if (smsKeyMap == null) {
            return Constants.ERROR_SMS_KEY_MAP;
        }
        String token = (String) smsKeyMap.get("token");
        String smsCode = generateSmsCode();
        HashMap<String, Object> redisRefreshSaveMap = new HashMap<>();
        redisRefreshSaveMap.put("smsCode", smsCode);
        redisRefreshSaveMap.put("token", token);
        redisCache.deleteObject(smsRealKey);
        redisCache.setCacheObject(smsRealKey, redisRefreshSaveMap, 300, TimeUnit.SECONDS);
        // 发送 smsCode 到用户手机
        LoginUser loginUser = tokenService.getLoginUserByJwtToken(token);
        if (!checkIsPhoneNumber(loginUser.getUser().getPhonenumber())) {
            return Constants.ERROR_PHONE_NOT_BIND;
        }
        return smsKey;
    }

    /**
     * 清除登录计数
     */
    public void clearLockLoginFor5times(String userName) {
        String redisUsernameKey = Constants.LOGIN_USER_NAME_KEY + userName;
        if (redisCache.getCacheObject(redisUsernameKey) != null) {
            redisCache.deleteObject(redisUsernameKey);
        }
    }

    public String generateSmsCode() {
        Random rnd = new Random();
        int number = rnd.nextInt(999999);
        return String.format("%06d", number);
    }

    public boolean checkIsPhoneNumber(String phoneNumber) {
        return phoneNumber != null;
    }

}
